package com.gxh.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxh.dto.SwiperDTO;
import com.gxh.dto.SwiperPageQueryDTO;
import com.gxh.entity.Swiper;
import com.gxh.mapper.SwiperMapper;
import com.gxh.result.PageResult;
import com.gxh.service.SwiperService;
import com.gxh.utils.AliOssUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SwiperServiceImpl implements SwiperService {

    @Autowired
    private SwiperMapper swiperMapper;
    @Autowired
    private AliOssUtil aliOssUtil;


    /**
     * 轮播图分页查询
     * @param swiperPageQueryDTO
     * @return
     */
    public PageResult pageQuery(SwiperPageQueryDTO swiperPageQueryDTO) {
        PageHelper.startPage(swiperPageQueryDTO.getPage(), swiperPageQueryDTO.getPageSize());
        Page<Swiper> page = swiperMapper.pageQuery(swiperPageQueryDTO);
        Long total = page.getTotal();
        List records = page.getResult();
        return new PageResult(total, records) ;
    }

    /**
     * 新增轮播图
     * @param swiperDTO
     */
    public void save(SwiperDTO swiperDTO) {
        Swiper swiper = new Swiper();
        BeanUtils.copyProperties(swiperDTO, swiper);


        swiperMapper.insertSwiper(swiper);
    }

    /**
     * 修改轮播图
     * @param swiperDTO
     */
    public void update(SwiperDTO swiperDTO) {
        Swiper swiper = new Swiper();
        BeanUtils.copyProperties(swiperDTO, swiper);
        swiperMapper.updateSwiper(swiper);
    }

    /**
     * 根据id查询轮播图
     * @param id
     * @return
     */
    public Swiper getById(Long id) {
        Swiper swiper = swiperMapper.selectById(id);
        return swiper;
    }

    /**
     * 批量删除轮播图
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {
        //获取轮播图信息
        List<Swiper> swiperList = swiperMapper.selectBatchIds(ids);
        //提取Oss中图片的key
        List<String> objectNames = swiperList.stream().map(
                swiper -> aliOssUtil.extractObjectName(swiper.getImgUrl()))
                .collect(Collectors.toList());
        //删除Oss中图片
        aliOssUtil.deleteBatchOss(objectNames);
        swiperMapper.deleteBatchIds(ids);
    }

    /**
     * 获取轮播图列表
     * @return
     */
    public List<Swiper> list() {
        List<Swiper> swiperList = swiperMapper.selectList(null);
        return swiperList;
    }
}
